package com.shhic.hhplt.server.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.shhic.hhplt.server.model.BoxNumber;
import com.shhic.hhplt.server.mapper.IBoxNumberDao;
import com.shhic.hhplt.server.service.IBoxNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@DS("hhpltSys")
@Transactional
public class BoxNumberServiceImpl implements IBoxNumberService {
    @Autowired
    private IBoxNumberDao boxNumberDao;
    private Map<String,Object> boxNumberLockMap = new HashMap<String, Object>();

    @Override
    public void insertOrUpdateBoxNumber(BoxNumber bn) {
        synchronized(getBoxNumberLock(bn.getCodeName())){
            BoxNumber oldSc = boxNumberDao.getBoxNumber(bn.getCodeName());
            if(oldSc == null){
                bn.setCount(0);
                bn.setCaseCode(0);
                boxNumberDao.insertBoxNumber(bn);
            }else{
                boxNumberDao.updateBoxNumber(bn);
            }
        }
        if(bn.isAvailable()){
            //如果是启用状态，则停用其他的
            boxNumberDao.disableOtherBoxNumberWithSameName(bn);
        }
    }

    @Override
    public void deleteBoxNumber(String codeName) {
        boxNumberDao.deleteBoxNumber(codeName);
    }

    @Override
    public Set<BoxNumber> getAllBoxNumber() {
        return boxNumberDao.getAllBoxNumber();
    }

    @Override
    public void updateNowBoxNumber(String codeName, String nowCode) {
        synchronized(getBoxNumberLock(codeName)){
            boxNumberDao.updateNowBoxNumber(codeName,nowCode);
        }
    }

    @Override
    public void addRetrivedCode(String codeName, String code) {
        synchronized(getBoxNumberLock(codeName)){
            boxNumberDao.insertRetrievedBoxNumber(codeName,code);
        }
    }

    @Override
    public boolean removeIfExistRetrievedCode(String codeName, String code) {
        synchronized(getBoxNumberLock(codeName)){
            return boxNumberDao.deleteRetrievedBoxNumber(codeName,code) != 0;
        }
    }

    @Override
    public BoxNumber getBoxNumber(String codeName) {
        return boxNumberDao.getBoxNumber(codeName);
    }

    private Object getBoxNumberLock(String codeName){
        synchronized(boxNumberLockMap){
            if(!boxNumberLockMap.containsKey(codeName)){
                boxNumberLockMap.put(codeName, new Object());
            }
            return boxNumberLockMap.get(codeName);
        }
    }
}
